package com.googlecode.jpocketmod;

import com.googlecode.jpocketmod.actions.ActionFactory;
import com.googlecode.jpocketmod.state.AppState;
import com.googlecode.jpocketmod.templates.PocketModTemplate;
import com.googlecode.jpocketmod.templates.pages.PageManager;
import com.googlecode.jpocketmod.templates.pages.PocketModPageInstance;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.GridLayout;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;

public class TemplatePanel extends JPanel {
	public TemplatePanel()  {
		super();
		
		if ( AppState.getInstance().getCurrentlyLoadedTemplate() == null )
			AppState.getInstance().setCurrentlyLoadedTemplate(new PocketModTemplate());
		
		reload();
	}
	
	public void reload()  {
		PocketModTemplate template = AppState.getInstance().getCurrentlyLoadedTemplate();
		
		this.setLayout(new GridLayout(template.getRows(),
									  template.getCols()));
		
		int numOfPages = template.getRows()*template.getCols();
		for ( int i=0 ; i<numOfPages ; i++ )  {
			PocketModPageInstance thisPageInstance = template.getPage(i);
			
			String displayText = "";
			ImageIcon thumbnailImage = new ImageIcon();
			
			try  {
				thumbnailImage = new ImageIcon(PageManager.getInstance().getPocketModPageImage(thisPageInstance));
			} catch (Exception ex)  {
				//TODO: Dialog manager call saying the Page could not be found
				displayText = "Could not load Page";
			}
			
			PageThumbnailButton thisPageButton = new PageThumbnailButton(displayText,
																		 thumbnailImage);
			thisPageButton.setAction(ActionFactory.getInstance().getChoosePageAction(i));
			this.add(thisPageButton);
		}
	}
}

class PageThumbnailButton extends JButton  {
	private String displayText = "";
	private ImageIcon thumbnail;
	private Image thumbnailImage, scaledImage;
	
	private int lastWidth, lastHeight;
	
	public PageThumbnailButton(String text, ImageIcon thumbnail)  {
		this.displayText = text;
		this.thumbnail = thumbnail;
		
		this.thumbnailImage = this.thumbnail.getImage();
		
		this.lastWidth = getWidth();
		this.lastHeight = getHeight();
	}
	
	@Override
	public void paintComponent(Graphics g)  {
		//super.paintComponent(g);
		
		if ( this.thumbnailImage != null )  {
			if ( lastWidth != getWidth() || lastHeight != getHeight() )  {
				scaledImage = thumbnailImage.getScaledInstance(getWidth(),
																getHeight(),
																Image.SCALE_SMOOTH);
				thumbnailImage.flush();
				scaledImage.flush();

				lastWidth = getWidth();
				lastHeight = getHeight();
			}

			g.drawImage(scaledImage, 0, 0, null);
		}
		
		//TODO: Draw centered text
	}
}
